package com.marco.ipdata.runnable;

import com.google.common.collect.Maps;
import com.marco.ipdata.service.ChinaIPService;
import com.marco.ipdata.service.impl.BaiduApiServiceImpl;
import com.marco.ipdata.service.impl.TaobaoApiServiceImpl;
import org.apache.commons.collections.CollectionUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * TaobaoApiRunnable.java
 * Create on 2017/3/23
 * Copyright(c) JD Inc 2017. All Rights Reserved.
 * <pre>
 * 功能说明：淘宝接口根据开启线程，进行遍历数据
 * </pre>
 */
@Service
@Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class TaobaoApiRunnable implements Runnable {
    private static final Logger logger = LoggerFactory.getLogger(TaobaoApiRunnable.class);
    //请求数据起始位置
    private Integer startIndex;
    //请求数据终止位置
    private Integer endIndex;
    //线程名称
    private String threadName;
    @Autowired
    private TaobaoApiServiceImpl taobaoApiService;
    @Autowired
    private ChinaIPService chinaIPService;

    @Override
    public void run() {
        this.setThreadName(threadName);
        Integer initStart = startIndex;
        logger.info("开启线程处理 淘宝 数据，请稍候---------------");
        while (true) {
            List<String> ipLists = chinaIPService.getIPListByFilters(startIndex);
            if (CollectionUtils.isEmpty(ipLists) || startIndex > endIndex) {
                startIndex = initStart;
                continue;
            }
            Integer size = ipLists.size();
            Map<String, String> param = Maps.newHashMap();
            for (String ip : ipLists) {
                param.put("ip", ip);
                taobaoApiService.invokeGet(param);
            }
            startIndex += size;
        }
    }

    public void setStartIndex(Integer startIndex) {
        this.startIndex = startIndex;
    }

    public void setThreadName(String threadName) {
        this.threadName = threadName;
    }

    public void setEndIndex(Integer endIndex) {
        this.endIndex = endIndex;
    }
}
